import {
	toast,
	clearStorageSync,
	getStorageSync,
	useRouter
} from './index'
import {
	BASE_URL
} from '@/config/index'
import RequestManager from '@/utils/requestManager.js'


const manager = new RequestManager()

const baseRequest = async ({
	url,
	method,
	data,
	loading,
	title
}) => {
	data = data || {}
	let requestId = manager.generateId(method, url, data)
	if (!requestId) {
		console.log('重复请求')
	}
	if (!requestId) return false;

	const header = {}
	if(getStorageSync("token")){
		header.Authorization ="Bearer "+getStorageSync('token')
	}
	else{
		header.Authorization =''
	}
	loading = loading || 'true'
	return new Promise((reslove, reject) => {
		(loading == 'true') && uni.showLoading({
			title: title || 'loading'
		})
		uni.request({
			url: BASE_URL + url,
			method: method || 'GET',
			header: header,
			timeout: 10000,
			data,
			complete: () => {
				(loading == 'true') && uni.hideLoading()
				manager.deleteById(requestId)
			},
			success: (successData) => {
				const res = successData.data||successData
				if (successData.statusCode == 200) {
					// 业务逻辑，自行修改
					if (res.code == 401) {
						reslove(res.data)
						uni.showModal({
							title: '系统提示',
							content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
							success: function(res2) {
								if (res2.confirm) {
									clearStorageSync()
									useRouter('/pages/login/login', 'reLaunch')
								} else if (res2.cancel) {}
							}
						});

					} else if (res.code == 200) {
						reslove(res)
					} else {
						toast(res.msg)

					}
				} else {
					toast('网络连接失败，请稍后重试')
					reject(res)
				}
			},
			fail: (msg) => {
				toast('网络连接失败，请稍后重试')
				reject(msg)

			}
		})
	})
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = ({
		url,
		data,
		loading,
		title
	}) => baseRequest({
		url,
		method,
		data,
		loading,
		title
	})
})

export default request